<?php
/******************************
 * EQdkp
 * Copyright 2002-2003
 * Licensed under the GNU GPL.  See COPYING for full terms.
 * ------------------
 * additemrequest.php
 * Began: Fri December 27 2002
 *
 *
 ******************************/

define('EQDKP_INC', true);
define('IN_ADMIN', true);
$eqdkp_root_path = './../';
include_once($eqdkp_root_path . 'common.php');

class Add_Item_Data extends EQdkp_Admin
{
    var $item     = array();            // Holds item data if URI_ITEM is set               @var item
    var $old_item = array();            // Holds item data from before POST                 @var old_item

    function add_item_data()
    {
        global $db, $eqdkp, $user, $tpl, $pm;
        global $eqdkp_root_path, $SID;

        parent::eqdkp_admin();

        $this->item = array(
            'item_name'        => post_or_db('item_name'),
            'item_jobs'        => post_or_db('item_jobs'),
            'dropped_from'     => post_or_db('dropped_from'),
            'item_level'       => post_or_db('item_level'),
            'data_row_one'     => post_or_db('data_row_one'),
            'data_row_two'     => post_or_db('data_row_two'),
            'data_row_three'   => post_or_db('data_row_three'),
            'data_row_four'    => post_or_db('data_row_four'),
            'data_row_five'    => post_or_db('data_row_five')
        );

        // Vars used to confirm deletion
        $this->set_vars(array(
            'confirm_text'  => $user->lang['confirm_delete_item'],
            'uri_parameter' => URI_ITEM)
        );

        $this->assoc_buttons(array(
            'add' => array(
                'name'    => 'add',
                'process' => 'process_add',
                'check'   => 'a_item_add'),
            'update' => array(
                'name'    => 'update',
                'process' => 'process_update',
                'check'   => 'a_item_upd'),
            'delete' => array(
                'name'    => 'delete',
                'process' => 'process_delete',
                'check'   => 'a_item_del'),
            'form' => array(
                'name'    => '',
                'process' => 'display_form',
                'check'   => 'a_item_'))
        );

        // Build the item array
        // ---------------------------------------------------------
        if ( $this->url_id )
        {
            $sql = 'SELECT item_name, item_jobs, item_level, dropped_from,
                           data_row_one, data_row_two, data_row_three, data_row_four,
                           data_row_five
                    FROM ' . ITEM_DATA_TABLE . "
                    WHERE item_data_id = '".$this->url_id."'";

            $result = $db->query($sql);
            if ( !$row = $db->fetch_record($result) )
            {
                message_die($user->lang['error_invalid_item_provided']);
            }
            $db->free_result($result);

            $this->item = array(
                'item_jobs'         => post_or_db('item_jobs', $row),
                'item_level'        => post_or_db('item_level', $row),
                'dropped_from'      => post_or_db('dropped_from', $row),
                'data_row_one'      => post_or_db('data_row_one', $row),
                'data_row_two'      => post_or_db('data_row_two', $row),
                'data_row_three'    => post_or_db('data_row_three', $row),
                'data_row_four'     => post_or_db('data_row_four', $row),
                'data_row_five'     => post_or_db('data_row_five', $row),
                'item_name'         => post_or_db('item_name',  $row)
            );
        }
    }

    function error_check()
    {
        global $user;

        if ( !empty($_POST['item_name']) )
        {
            $this->item['item_name'] = $_POST['item_name'];
        }
        else
        {
            $this->fv->errors['item_name'] = $user->lang['fv_required_item_name'];
        }

        return $this->fv->is_error();
    }

    // ---------------------------------------------------------
    // Process Add
    // ---------------------------------------------------------
    function process_add()
    {
        global $db, $eqdkp, $user, $tpl, $pm;
        global $eqdkp_root_path, $SID;

        # Make sure we have something to set
        if (empty($this->item['item_name']))
        {
            $failure_message = "Failed to add item data for item: no item name specified";
            $link_list = array(
                'Add Item Data'     => 'additemdata.php' . $SID,
                'List Item Data'    => 'listitemdata.php'. $SID);
            $this->admin_die($failure_message, $link_list);
        }

        $item_data_id = -1;
        $sql = 'SELECT item_data_id
                FROM '. ITEM_DATA_TABLE ."
                WHERE item_name = '".$this->item['item_name']."'";

        $result = $db->query($sql);

        while ( $row = $db->fetch_record($result) )
        {
            $item_data_id = $row['item_data_id'];
        }

        $db->free_result($result);

        # Don't allow duplicate item names
        if ($item_data_id != -1)
        {
            $failure_message = "Failed to add item data for item: ".$this->item['item_name'].", item name already exists";
            $link_list = array(
                'Add Item Data'   => 'additemdata.php' . $SID,
                'List Item Data' => 'listitemdata.php' . $SID);
            $this->admin_die($failure_message, $link_list);
        }

        //
        // Add the item data to the database
        //
        $this->add_new_item($item_data_id);

        //
        // Logging
        //
        $log_action = array(
            'header'       => '{L_ACTION_ITEM_DATA_ADDED}',
            '{L_NAME}'     => $this->item['item_name'],
            '{L_ADDED_BY}' => $this->admin_user);
        $this->log_insert(array(
            'log_type'   => $log_action['header'],
            'log_action' => $log_action)
        );

        //
        // Success message
        //
        $success_message = sprintf($user->lang['admin_add_item_data_success'], $this->item['item_name']);
        $link_list = array(
            'Add Item Data'   => 'additemdata.php' . $SID,
            'List Item Data' => 'listitemdata.php' . $SID);
        $this->admin_die($success_message, $link_list);
    }

    // ---------------------------------------------------------
    // Process Update
    // ---------------------------------------------------------
    function process_update()
    {
        global $db, $eqdkp, $user, $tpl, $pm;
        global $eqdkp_root_path, $SID;

        # Make sure we have something to set
        if (empty($this->item['item_name']))
        {
            $failure_message = "Failed to add item data for item: no item name specified";
            $link_list = array(
                'Add Item Data'     => 'additemdata.php' . $SID,
                'List Item Data'    => 'listitemdata.php'. $SID);
            $this->admin_die($failure_message, $link_list);
        }

        $item_data_id = -1;
        $sql = 'SELECT item_data_id
                FROM '. ITEM_DATA_TABLE ."
                WHERE item_name = '".$this->item['item_name']."'";

        $result = $db->query($sql);

        while ( $row = $db->fetch_record($result) )
        {
            $item_data_id = $row['item_data_id'];
        }

        $db->free_result($result);

        //
        // Remove the old item
        //
        $this->remove_old_item($item_data_id);


        //
        // Add the item data
        //
        $this->add_new_item();

        //
        // Logging
        //
        $log_action = array(
            'header'             => '{L_ACTION_ITEM_DATA_UPDATED}',
            '{L_NAME_BEFORE}'    => $this->old_item['item_name'],
            '{L_NAME_AFTER}'     => $this->find_difference($this->old_item['item_name'], $this->item['item_name']),
            '{L_UPDATED_BY}'     => $this->admin_user);
        $this->log_insert(array(
            'log_type'   => $log_action['header'],
            'log_action' => $log_action)
        );

        //
        // Success message
        //
        $success_message = sprintf($user->lang['admin_update_item_data_success'], $this->old_item['item_name']);
        $link_list = array(
            'Add Item Data'   => 'additemdata.php' . $SID,
            'List Item Data' => 'listitemdata.php' . $SID);
        $this->admin_die($success_message, $link_list);
    }

    function process_complete()
    {
        global $db, $eqdkp, $user, $tpl, $pm;
        global $eqdkp_root_path, $SID;

        // Get item name from the appropriate field
        $this->item['item_name'] = ( !empty($_POST['item_name']) ) ? $_POST['item_name'] : $_POST['select_item_name'];

        // Update the item_requesters list to have quotes added
        foreach ($_POST['item_requesters'] as $req_key=>$req_value)
        {
            $members[$req_key] = "'".$req_value."'";
        }
        // Update the database 
    
        // Build our list of users
        $member_list = join(',', $members);

        // Update request(s) in item request table
        //
        $sql = 'UPDATE '. ITEM_REQUEST_TABLE ."
                SET request_fulfilled = 1,
                    item_updated_by = '".$this->admin_user."'
                WHERE item_name = '".$this->item['item_name']."' 
                AND item_requester in (".$member_list.")";
        $db->query($sql);


        //
        // Success message
        //
        $success_message = sprintf($user->lang['admin_complete_item_req_success'], $this->item['item_name'], implode(', ', $this->item['item_requesters']));
        $link_list = array(
            'Add Item Request'   => 'additemrequest.php' . $SID,
            'List Item Requests' => 'listitemrequest.php' . $SID);
        $this->admin_die($success_message, $link_list);

    }
    // ---------------------------------------------------------
    // Process Delete (confirmed)
    // ---------------------------------------------------------
    function process_confirm()
    {
        global $db, $eqdkp, $user, $tpl, $pm;
        global $eqdkp_root_path, $SID;

        //
        // Remove the old item
        //
        $this->remove_old_item($this->url_id);

        //
        // Logging
        //
        $log_action = array(
            'header'      => '{L_ACTION_ITEM_DATA_DELETED}',
            '{L_NAME}'    => $this->old_item['item_name']
        );
        $this->log_insert(array(
            'log_type'   => $log_action['header'],
            'log_action' => $log_action)
        );

        //
        // Success message
        //
        $success_message = sprintf($user->lang['admin_delete_item_data_success'], $this->old_item['item_name']);
        $link_list = array(
            'Add Item Data'     => 'additemdata.php' . $SID,
            'List Item Data'    => 'listitemdata.php'. $SID);
        $this->admin_die($success_message, $link_list);
    }

    // ---------------------------------------------------------
    // Process helper methods
    // ---------------------------------------------------------
    function remove_old_item($item_data_id)
    {
        global $db;

        //
        // Build the old_item array
        //
        $sql = 'SELECT item_name, item_jobs, item_level, dropped_from,
                       data_row_one, data_row_two, data_row_three, data_row_four,
                       data_row_five
                FROM ' . ITEM_DATA_TABLE . "
                WHERE item_data_id = '".$item_data_id."'";

        $result = $db->query($sql);
        if ( !$row = $db->fetch_record($result) )
        {
            message_die($user->lang['error_invalid_item_provided']);
        }
        $db->free_result($result);

        $this->old_item = array(
            'item_jobs'         => post_or_db('item_jobs', $row),
            'item_level'        => post_or_db('item_level', $row),
            'dropped_from'      => post_or_db('dropped_from', $row),
            'data_row_one'      => post_or_db('data_row_one', $row),
            'data_row_two'      => post_or_db('data_row_two', $row),
            'data_row_three'    => post_or_db('data_row_three', $row),
            'data_row_four'     => post_or_db('data_row_four', $row),
            'data_row_five'     => post_or_db('data_row_five', $row),
            'item_name'         => post_or_db('item_name',  $row)
        );

        //
        // Remove the item data from the table
        //
        $sql = 'DELETE FROM ' . ITEM_DATA_TABLE . "
                WHERE item_data_id = '".$item_data_id."'";

        $db->query($sql);
    }

    function add_new_item()
    {
        global $db;

        $jobs = '';
        foreach ($this->item['item_jobs'] as $job)
        {
            $jobs = $jobs.' '.stripslashes($job);
        }

        $query = $db->build_query('INSERT', array(
                'item_name'     => stripslashes($this->item['item_name']),
                'data_row_one'  => ( $this->item['data_row_one'] ) ? stripslashes($this->item['data_row_one']): '',
                'data_row_two'  => ( $this->item['data_row_two'] ) ? stripslashes($this->item['data_row_two']): '',
                'data_row_three'=> ( $this->item['data_row_three'] ) ? stripslashes($this->item['data_row_three']): '',
                'data_row_four' => ( $this->item['data_row_four'] ) ? stripslashes($this->item['data_row_four']): '',
                'data_row_five' => ( $this->item['data_row_five'] ) ? stripslashes($this->item['data_row_five']): '',
                'item_level'    => stripslashes($this->item['item_level']),
                'dropped_from'  => stripslashes($this->item['dropped_from']),
                'item_jobs'     => $jobs,
                'added_by'      => $this->admin_user)
        );

        $query = preg_replace('#^.+\) VALUES (\(.+\))#', '\1', $query);

        $sql = 'INSERT INTO ' . ITEM_DATA_TABLE . '
                (item_name, data_row_one, data_row_two, data_row_three, data_row_four,
                 data_row_five, item_level, dropped_from, item_jobs, added_by)
                VALUES '. $query;

        $db->query($sql);
    }

    // ---------------------------------------------------------
    // Display form
    // ---------------------------------------------------------
    function display_form()
    {
        global $db, $eqdkp, $user, $tpl, $pm;
        global $eqdkp_root_path, $SID;

        //
        // Build the list of available classes
        //
        $sql = 'SELECT class_name, class_short_name
                FROM '. CLASS_TABLE .'
                ORDER BY class_name';

        $result = $db->query($sql);

        if (!is_array($this->item['item_jobs']))
        {
            $this->item['item_jobs'] = split(' ', $this->item['item_jobs']);
        }

        while ( $row = $db->fetch_record($result) )
        {
            $selected = '';
            if (isset($this->item['item_jobs']) && is_array($this->item['item_jobs']))
            {
                foreach ($this->item['item_jobs'] as $job_name)
                {
                    if ($job_name == $row['class_short_name'])
                    {
                        $selected = ' checked';
                    }
                }
            }

            $tpl->assign_block_vars('class_row', array(
                'VALUE' => $row['class_short_name'],
                'SELECTED' => $selected,
                'OPTION' => $row['class_name'])
            );

        }

        $db->free_result($result);

        if (isset($this->url_id))
        {
            $sql = "SELECT * FROM ".ITEM_DATA_TABLE." 
                    WHERE item_data_id = '".$this->url_id."'";
            $result = $db->query($sql);
            while ( $row = $db->fetch_record($result) )
            {
                $this->item['item_jobs']       = post_or_db('item_jobs', $row);
                $this->item['item_level']      = post_or_db('item_level', $row);
                $this->item['dropped_from']    = post_or_db('dropped_from', $row);
                $this->item['data_row_one']    = post_or_db('data_row_one', $row);
                $this->item['data_row_two']    = post_or_db('data_row_two', $row);
                $this->item['data_row_three']  = post_or_db('data_row_three', $row);
                $this->item['data_row_four']   = post_or_db('data_row_four', $row);
                $this->item['data_row_five']   = post_or_db('data_row_five', $row);
                $this->item['item_name']       = post_or_db('item_name',  $row);
            }
        }

        $tpl->assign_vars(array(
            // Form vars
            'F_ADD_ITEM_DATA'   => 'additemdata.php' .$SID,
            'ITEM_ID'           => $this->url_id,

            // Form values
            'ITEM_NAME'             => stripslashes($this->item['item_name']),
            'ITEM_LEVEL'            => stripslashes($this->item['item_level']),
            'DROPPED_FROM'          => stripslashes($this->item['dropped_from']),
            'DATA_ROW_ONE'          => stripslashes($this->item['data_row_one']),
            'DATA_ROW_TWO'          => stripslashes($this->item['data_row_two']),
            'DATA_ROW_THREE'          => stripslashes($this->item['data_row_three']),
            'DATA_ROW_FOUR'          => stripslashes($this->item['data_row_four']),
            'DATA_ROW_FIVE'          => stripslashes($this->item['data_row_five']),

            // Language
            'L_ADD_ITEM_DATA_TITLE' => $user->lang['additemdata_title'],
            'L_ADD_ITEM_DATA'       => $user->lang['add_item_data'],
            'L_DELETE_ITEM_DATA'    => $user->lang['delete_item_data'],
            'L_UPDATE_ITEM_DATA'    => $user->lang['update_item_data'],
            'L_ITEM_NAME'           => $user->lang['item_name'],
            'L_ITEM_LEVEL'          => $user->lang['item_level'],
            'L_ITEM_JOBS'           => $user->lang['item_classes'],
            'L_DROPPED_FROM'        => $user->lang['dropped_from'],
            'L_DATA_ROW_1'          => $user->lang['data_row_one'],
            'L_DATA_ROW_2'          => $user->lang['data_row_two'],
            'L_DATA_ROW_3'          => $user->lang['data_row_three'],
            'L_DATA_ROW_4'          => $user->lang['data_row_four'],
            'L_DATA_ROW_5'          => $user->lang['data_row_five'],

            'L_REQUESTERS'              => $user->lang['requesters'],
            'L_HOLD_CTRL_NOTE'      => '('.$user->lang['hold_ctrl_note'].')<br />',
            'L_SEARCH_MEMBERS'      => $user->lang['search_members'],
            'L_NOTE'                => $user->lang['note'],
            'L_ITEM'                => $user->lang['item'],
            'L_SEARCH'              => strtolower($user->lang['search']),
            'L_SEARCH_EXISTING'     => $user->lang['search_existing'],
            'L_SELECT_EXISTING'     => $user->lang['select_existing'],
            'L_OR'                  => strtolower($user->lang['or']),
            'L_ENTER_NEW'           => $user->lang['enter_new'],
            'L_VALUE'               => $user->lang['value'],
            'L_ADD_ITEM'            => $user->lang['add_item_req'],
            'L_RESET'               => $user->lang['reset'],
            'L_UPDATE_ITEM'         => $user->lang['update_item_req'],
            'L_DELETE_ITEM'         => $user->lang['delete_item_req'],
            'L_FULFILL_REQUEST'     => $user->lang['complete_item_req'],

            // Form validation
            'FV_ITEM_REQUESTERS' => $this->fv->generate_error('item_requesters'),
            'FV_ITEM_NAME'   => $this->fv->generate_error('item_name'),

            // Javascript messages
            'MSG_NAME_EMPTY'    => $user->lang['fv_required_item_name'],
            'MSG_VALUE_EMPTY'   => $user->lang['fv_required_value'],

            // Buttons
            'S_ADD' => ( !$this->url_id ) ? true : false)
        );

        $eqdkp->set_vars(array(
            'page_title'    => sprintf($user->lang['admin_title_prefix'], $eqdkp->config['guildtag'], $eqdkp->config['dkp_name']).': '.$user->lang['additemdata_title'],
            'template_file' => 'admin/additemdata.html',
            'display'       => true)
        );
    }
}

class Item_Req_Search extends EQdkp_Admin
{
    function item_req_search()
    {
        global $db, $eqdkp, $user, $tpl, $pm;
        global $SID;

        parent::eqdkp_admin();

        $this->assoc_buttons(array(
            'search' => array(
                'name'    => 'search',
                'process' => 'process_search',
                'check'   => 'a_item_'),
            'form' => array(
                'name'    => '',
                'process' => 'display_form',
                'check'   => 'a_item_'))
        );
    }

    function error_check()
    {
        $this->fv->is_filled('query');
        if ( strlen($_POST['query']) < 2 )
        {
            $this->fv->errors['query'] = '';
        }

        return $this->fv->is_error();
    }

    // ---------------------------------------------------------
    // Process item search
    // ---------------------------------------------------------
    function process_search()
    {
        global $db, $eqdkp, $user, $tpl, $pm;
        global $SID;

        $items_array = array();
        if ( !empty($_POST['query']) )
        {
            $eqdkp_items      = array();
            $eqdkp_item_stats = array();

            //
            // Get item names from our standard items table
            //
            $sql = 'SELECT item_name
                    FROM ' . ITEM_REQUEST_TABLE . "
                    WHERE item_name LIKE '%" . $_POST['query'] . "%'
                    ORDER BY item_name";
            $result = $db->query($sql);
            while ( $row = $db->fetch_record($result) )
            {
                $eqdkp_items[] = $row['item_name'];
            }
            $db->free_result($result);

            //
            // Get item names from our stats table if the stats plugin is installed
            //

            // #######################################
            // Alteration sumbitted by Tam
            // #######################################
            if ( $pm->check(PLUGIN_INSTALLED, 'stats') )
                  {
                      $sql = 'SELECT name
                              FROM ' . ITEM_STATS_TABLE . "
                              WHERE name LIKE '%" . $_POST['query'] . "%'
                              ORDER BY name";
                      $result = $db->query($sql);
                      while ( $row = $db->fetch_record($result) )
                      {
                          // Add the item if we don't have it already
                          if ( !in_array($row['item_name'], $eqdkp_items) )
                          {
                              $eqdkp_item_stats[] = $row['name'];
                          }
                      }
                      $db->free_result($result);
                  }
            //#######################################

            //
            // Build the drop-down
            //
            $items_array = array_merge($eqdkp_items, $eqdkp_item_stats);
            $items_array = array_unique($items_array);
            sort($items_array);
            reset($items_array);

            foreach ( $items_array as $item_name )
            {
                $tpl->assign_block_vars('items_row', array(
                    'VALUE'  => stripslashes($item_name),
                    'OPTION' => stripslashes($item_name))
                );
            }
        }

        $tpl->assign_vars(array(
            'S_STEP1' => false,

            'L_RESULTS' => sprintf($user->lang['results'], sizeof($items_array), stripslashes($_POST['query'])),
            'L_SELECT'  => $user->lang['select'])
        );

        $eqdkp->set_vars(array(
            'page_title'        => sprintf($user->lang['admin_title_prefix'], $eqdkp->config['guildtag'], $eqdkp->config['dkp_name']).': '.$user->lang['additemdata_title'],
            'gen_simple_header' => true,
            'template_file'     => 'admin/additemdata_search.html',
            'display'           => true)
        );
    }

    // ---------------------------------------------------------
    // Display item search
    // ---------------------------------------------------------
    function display_form()
    {
        global $db, $eqdkp, $user, $tpl, $pm;
        global $SID;

        $tpl->assign_vars(array(
            'F_SEARCH_ITEM' => 'additemrequest.php' . $SID . '&amp;mode=search',
            'S_STEP1'       => true,
            'ONLOAD'        => ' onload="javascript:document.post.query.focus()"',

            'L_ITEM_SEARCH'  => $user->lang['item_search'],
            'L_SEARCH'       => $user->lang['search'],
            'L_CLOSE_WINDOW' => $user->lang['close_window'])
        );

        $eqdkp->set_vars(array(
            'page_title'        => sprintf($user->lang['admin_title_prefix'], $eqdkp->config['guildtag'], $eqdkp->config['dkp_name']).': '.$user->lang['additemdata_title'],
            'gen_simple_header' => true,
            'template_file'     => 'admin/additemdata_search.html',
            'display'           => true)
        );
    }
}

$mode = ( isset($_GET['mode']) ) ? $_GET['mode'] : 'additemrequest';

switch ( $mode )
{
    case 'additemrequest':
        $add_item = new Add_Item_Data;
        $add_item->process();
        break;

    case 'search':
        $item_search = new Item_Req_Search;
        $item_search->process();
        break;
}
?>
